//
//  Common.cpp
//  KeepPwd
//
//  Created by lzh on 2017/11/11.
//  Copyright © 2017年 LZH. All rights reserved.
//

#include "Common.hpp"
unsigned char* CCommonB::intToByteArray(int integer){
    int byteNum = (40 - CCommonB::numberOfLeadingZeros(integer < 0 ? ~integer
                                                     : integer)) / 8;
    static unsigned char byteArray[4];
    for (int n = 0; n < byteNum; n++)
        byteArray[3 - n] = (unsigned char)(((unsigned int)integer) >> (n * 8));
    return (byteArray);
}

int CCommonB::byteArrayToInt(unsigned char* b, int offset){
    int value = 0;
    for (int i = 0; i < 4; i++) {
        int shift = (4 - 1 - i) * 8;
        value += (b[i + offset] & 0x000000FF) << shift;
    }
    return value;
}

int CCommonB::numberOfLeadingZeros(int i){
    if (i == 0)
        return 32;
    int n = 1;
    if (((unsigned int)i) >> 16 == 0) { n += 16; i <<= 16; }
    if (((unsigned int)i) >> 24 == 0) { n +=  8; i <<=  8; }
    if (((unsigned int)i) >> 28 == 0) { n +=  4; i <<=  4; }
    if (((unsigned int)i) >> 30 == 0) { n +=  2; i <<=  2; }
    n -= ((unsigned int)i) >> 31;
    return n;
}

